<template>
	<view class="chat-session-container">
		<view class="header">
			<view class="search-box">
				<input 
					type="text" 
					v-model="searchKeyword" 
					placeholder="搜索会话ID或用户ID" 
					@input="handleSearch"
				/>
				<text class="search-icon">🔍</text>
			</view>
			<view class="filter-box">
				<view class="date-range">
					<picker mode="date" :value="startDate" @change="onStartDateChange">
						<view class="picker-item">
							<text>开始日期: {{ startDate || '选择开始日期' }}</text>
						</view>
					</picker>
					<text>至</text>
					<picker mode="date" :value="endDate" @change="onEndDateChange">
						<view class="picker-item">
							<text>结束日期: {{ endDate || '选择结束日期' }}</text>
						</view>
					</picker>
				</view>
				<view class="status-filter">
					<text>状态: </text>
					<picker :range="statusOptions" :value="statusIndex" @change="onStatusChange">
						<view class="picker-item">
							<text>{{ statusOptions[statusIndex] }}</text>
						</view>
					</picker>
				</view>
			</view>
			<button class="search-btn" @click="loadSessions">查询</button>
			<button class="reset-btn" @click="resetFilters">重置</button>
		</view>
		
		<view class="session-list">
			<view class="list-header">
				<text class="column session-id">会话ID</text>
				<text class="column user-id">用户ID</text>
				<text class="column service-id">客服ID</text>
				<text class="column status">状态</text>
				<text class="column start-time">开始时间</text>
				<text class="column end-time">结束时间</text>
				<text class="column duration">持续时间</text>
				<text class="column operation">操作</text>
			</view>
			
			<view class="list-body">
				<view v-if="loading" class="loading">
					<text>加载中...</text>
				</view>
				<view v-else-if="sessions.length === 0" class="no-data">
					<text>暂无会话数据</text>
				</view>
				<view 
					v-else
					v-for="(session, index) in sessions" 
					:key="session.id" 
					class="session-item"
					:class="{ 'odd-row': index % 2 === 1 }"
				>
					<text class="column session-id">{{ session.sessionId }}</text>
					<text class="column user-id">{{ session.userId }}</text>
					<text class="column service-id">{{ session.serviceId }}</text>
					<text class="column status" :class="'status-' + session.status">
						{{ formatStatus(session.status) }}
					</text>
					<text class="column start-time">{{ formatTime(session.startTime) }}</text>
					<text class="column end-time">{{ session.endTime ? formatTime(session.endTime) : '-' }}</text>
					<text class="column duration">{{ calculateDuration(session.startTime, session.endTime) }}</text>
					<view class="column operation">
						<button class="detail-btn" @click="viewDetail(session)">详情</button>
						<button 
							v-if="session.status === 'ACTIVE'" 
							class="end-btn" 
							@click="endSession(session)"
						>
							结束
						</button>
					</view>
				</view>
			</view>
		</view>
		
		<view class="pagination">
			<button 
				:disabled="currentPage <= 1" 
				@click="prevPage"
			>
				上一页
			</button>
			<text>{{ currentPage }} / {{ totalPages }}</text>
			<button 
				:disabled="currentPage >= totalPages" 
				@click="nextPage"
			>
				下一页
			</button>
		</view>
		
		<!-- 会话详情弹窗 -->
		<view v-if="showDetailModal" class="modal-overlay" @click="closeDetailModal">
			<view class="modal-content" @click.stop>
				<view class="modal-header">
					<text class="modal-title">会话详情</text>
					<text class="modal-close" @click="closeDetailModal">×</text>
				</view>
				<view class="modal-body">
					<view v-if="detailLoading" class="loading">加载中...</view>
					<view v-else>
						<view class="detail-row">
							<text class="detail-label">会话ID:</text>
							<text class="detail-value">{{ currentSession.sessionId }}</text>
						</view>
						<view class="detail-row">
							<text class="detail-label">用户ID:</text>
							<text class="detail-value">{{ currentSession.userId }}</text>
						</view>
						<view class="detail-row">
							<text class="detail-label">客服ID:</text>
							<text class="detail-value">{{ currentSession.serviceId }}</text>
						</view>
						<view class="detail-row">
							<text class="detail-label">状态:</text>
							<text class="detail-value">{{ formatStatus(currentSession.status) }}</text>
						</view>
						<view class="detail-row">
							<text class="detail-label">开始时间:</text>
							<text class="detail-value">{{ formatTime(currentSession.startTime) }}</text>
						</view>
						<view class="detail-row">
							<text class="detail-label">结束时间:</text>
							<text class="detail-value">{{ currentSession.endTime ? formatTime(currentSession.endTime) : '-' }}</text>
						</view>
						<view class="detail-row">
							<text class="detail-label">持续时间:</text>
							<text class="detail-value">{{ calculateDuration(currentSession.startTime, currentSession.endTime) }}</text>
						</view>
						
						<view class="messages-title">会话消息</view>
						<view class="messages-list">
							<view 
								v-for="(message, index) in sessionMessages" 
								:key="index"
								class="message-item"
								:class="{ 'user-message': message.role === 'user', 'service-message': message.role === 'assistant' }"
							>
								<view class="message-header">
									<text class="message-role">{{ message.role === 'user' ? '用户' : '客服' }}</text>
									<text class="message-time">{{ formatTime(message.createTime) }}</text>
								</view>
								<view class="message-content">{{ message.content }}</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { getSessionList, getSessionDetail, getSessionMessages, endSession } from '@/api/chatSession.js';
	
	export default {
		data() {
			return {
				sessions: [],
				loading: false,
				searchKeyword: '',
				startDate: '',
				endDate: '',
				statusOptions: ['全部', '活跃', '已结束'],
				statusIndex: 0,
				currentPage: 1,
				pageSize: 10,
				totalPages: 1,
				totalCount: 0,
				
				// 详情弹窗
				showDetailModal: false,
				currentSession: {},
				sessionMessages: [],
				detailLoading: false
			}
		},
		mounted() {
			this.loadSessions();
		},
		methods: {
			// 加载会话列表
			async loadSessions() {
				try {
					this.loading = true;
					
					// 构建查询参数
					const params = {
						current: this.currentPage,
						pageSize: this.pageSize,
						keyword: this.searchKeyword,
						status: this.statusIndex === 0 ? '' : 
								this.statusIndex === 1 ? 'ACTIVE' : 'ENDED',
						startDate: this.startDate,
						endDate: this.endDate
					};
					
					const res = await getSessionList(params);
					this.sessions = res.data.records;
					this.totalCount = res.data.total;
					this.totalPages = Math.ceil(this.totalCount / this.pageSize);
				} catch (error) {
					console.error('加载会话列表失败:', error);
					uni.showToast({
						title: '加载会话列表失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},
			
			// 查看会话详情
			async viewDetail(session) {
				try {
					this.detailLoading = true;
					this.showDetailModal = true;
					this.currentSession = session;

					// 加载会话详情
					const detailRes = await getSessionDetail(session.sessionId);
					this.currentSession = detailRes.data;

					// 加载会话消息
					const messagesRes = await getSessionMessages(session.sessionId, {
						current: 1,
						pageSize: 100
					});
					this.sessionMessages = messagesRes.data.records;
				} catch (error) {
					console.error('加载会话详情失败:', error);
					uni.showToast({
						title: '加载会话详情失败',
						icon: 'none'
					});
				} finally {
					this.detailLoading = false;
				}
			},
			
			// 关闭详情弹窗
			closeDetailModal() {
				this.showDetailModal = false;
				this.currentSession = {};
				this.sessionMessages = [];
			},
			
			// 结束会话
			async endSession(session) {
				try {
					const res = await endSession(session.sessionId, 'ADMIN_FORCE_END');
					if (res.code === 200) {
						uni.showToast({
							title: '会话已结束',
							icon: 'success'
						});
						this.loadSessions();
					} else {
						uni.showToast({
							title: res.message || '结束会话失败',
							icon: 'none'
						});
					}
				} catch (err) {
					uni.showToast({
						title: '结束会话失败',
						icon: 'none'
					});
				}
			},
			
			// 分页相关
			prevPage() {
				if (this.currentPage > 1) {
					this.currentPage--;
					this.loadSessions();
				}
			},
			nextPage() {
				if (this.currentPage < this.totalPages) {
					this.currentPage++;
					this.loadSessions();
				}
			},
			
			// 筛选相关
			handleSearch() {
				this.currentPage = 1;
			},
			onStartDateChange(e) {
				this.startDate = e.detail.value;
			},
			onEndDateChange(e) {
				this.endDate = e.detail.value;
			},
			onStatusChange(e) {
				this.statusIndex = parseInt(e.detail.value);
			},
			resetFilters() {
				this.searchKeyword = '';
				this.startDate = '';
				this.endDate = '';
				this.statusIndex = 0;
				this.currentPage = 1;
				this.loadSessions();
			},
			
			// 格式化和计算相关
			formatStatus(status) {
				switch(status) {
					case 'ACTIVE': return '活跃';
					case 'ENDED': return '已结束';
					default: return status;
				}
			},
			formatTime(time) {
				if (!time) return '-';
				return new Date(time).toLocaleString();
			},
			calculateDuration(startTime, endTime) {
				if (!startTime) return '-';
				
				const start = new Date(startTime).getTime();
				const end = endTime ? new Date(endTime).getTime() : Date.now();
				const durationMs = end - start;
				
				// 转换为可读格式
				const seconds = Math.floor((durationMs / 1000) % 60);
				const minutes = Math.floor((durationMs / (1000 * 60)) % 60);
				const hours = Math.floor((durationMs / (1000 * 60 * 60)) % 24);
				
				if (hours > 0) {
					return `${hours}小时${minutes}分钟`;
				} else if (minutes > 0) {
					return `${minutes}分钟${seconds}秒`;
				} else {
					return `${seconds}秒`;
				}
			}
		}
	}
</script>

<style>
	.chat-session-container {
		padding: 20px;
		height: 100%;
		display: flex;
		flex-direction: column;
	}
	
	.header {
		display: flex;
		flex-wrap: wrap;
		gap: 10px;
		margin-bottom: 20px;
		padding-bottom: 15px;
		border-bottom: 1px solid #e0e0e0;
	}
	
	.search-box {
		position: relative;
		width: 300px;
	}
	
	.search-box input {
		width: 100%;
		padding: 8px 12px;
		padding-right: 35px;
		border: 1px solid #ddd;
		border-radius: 4px;
	}
	
	.search-icon {
		position: absolute;
		right: 10px;
		top: 50%;
		transform: translateY(-50%);
	}
	
	.filter-box {
		display: flex;
		gap: 15px;
		align-items: center;
	}
	
	.date-range {
		display: flex;
		align-items: center;
		gap: 5px;
	}
	
	.picker-item {
		padding: 8px 12px;
		border: 1px solid #ddd;
		border-radius: 4px;
		background-color: #f9f9f9;
	}
	
	.status-filter {
		display: flex;
		align-items: center;
		gap: 5px;
	}
	
	.search-btn, .reset-btn {
		padding: 8px 15px;
	}
	
	.search-btn {
		background-color: #007AFF;
		color: white;
	}
	
	.reset-btn {
		background-color: #f2f2f2;
	}
	
	.session-list {
		flex: 1;
		overflow: auto;
		border: 1px solid #e0e0e0;
		border-radius: 4px;
	}
	
	.list-header {
		display: flex;
		padding: 12px 15px;
		background-color: #f2f2f2;
		font-weight: bold;
	}
	
	.list-body {
		min-height: 200px;
	}
	
	.session-item {
		display: flex;
		padding: 12px 15px;
		border-bottom: 1px solid #e0e0e0;
	}
	
	.odd-row {
		background-color: #f9f9f9;
	}
	
	.column {
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	
	.session-id, .user-id, .service-id {
		width: 12%;
	}
	
	.status {
		width: 8%;
	}
	
	.start-time, .end-time {
		width: 15%;
	}
	
	.duration {
		width: 10%;
	}
	
	.operation {
		width: 16%;
		display: flex;
		gap: 5px;
	}
	
	.detail-btn, .end-btn {
		padding: 4px 8px;
		font-size: 14px;
	}
	
	.detail-btn {
		background-color: #007AFF;
		color: white;
	}
	
	.end-btn {
		background-color: #FF3B30;
		color: white;
	}
	
	.status-ACTIVE {
		color: #34C759;
	}
	
	.status-ENDED {
		color: #8E8E93;
	}
	
	.loading, .no-data {
		padding: 40px;
		text-align: center;
		color: #8E8E93;
	}
	
	.pagination {
		display: flex;
		justify-content: center;
		align-items: center;
		gap: 15px;
		margin-top: 20px;
	}
	
	.modal-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 999;
	}
	
	.modal-content {
		width: 80%;
		max-width: 900px;
		max-height: 80vh;
		background-color: white;
		border-radius: 8px;
		display: flex;
		flex-direction: column;
	}
	
	.modal-header {
		display: flex;
		justify-content: space-between;
		padding: 15px 20px;
		border-bottom: 1px solid #e0e0e0;
	}
	
	.modal-title {
		font-size: 18px;
		font-weight: bold;
	}
	
	.modal-close {
		font-size: 24px;
		cursor: pointer;
	}
	
	.modal-body {
		padding: 20px;
		overflow-y: auto;
	}
	
	.detail-row {
		display: flex;
		margin-bottom: 10px;
	}
	
	.detail-label {
		width: 100px;
		font-weight: bold;
	}
	
	.messages-title {
		font-size: 16px;
		font-weight: bold;
		margin: 20px 0 10px;
	}
	
	.messages-list {
		border: 1px solid #e0e0e0;
		border-radius: 4px;
		max-height: 400px;
		overflow-y: auto;
	}
	
	.message-item {
		padding: 10px 15px;
		border-bottom: 1px solid #e0e0e0;
	}
	
	.message-header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 5px;
	}
	
	.message-role {
		font-weight: bold;
	}
	
	.message-time {
		color: #8E8E93;
		font-size: 12px;
	}
	
	.message-content {
		word-break: break-word;
	}
	
	.user-message {
		background-color: #f2f7ff;
	}
	
	.service-message {
		background-color: #f9f9f9;
	}
</style> 